<include file="header"/>
<link rel="stylesheet" href="/assets/base/restaurant/css/default.css"/>
<link rel="stylesheet" href="/assets/base/restaurant/css/component.css"/>
<link rel="stylesheet" href="/assets/base/repair/js/sweetalert/lib/sweet-alert.css">
<body>
<div class="wraper">
    <div class="load">
        <img class="load-bee" src="/assets/base/restaurant/images/load-bee.png"/>
    </div>
    <div class="scrm-loadding">
        <svg width="95" height="20" id="gb-loading">
            <rect width="20" height="20" x="0" y="0" rx="3" ry="3">
                <animate attributeName="width" values="0;20;20;20;0" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="height" values="0;20;20;20;0" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="x" values="10;0;0;0;10" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="y" values="10;0;0;0;10" dur="1000ms" repeatCount="indefinite"/>
            </rect>
            <rect width="20" height="20" x="25" y="0" rx="3" ry="3">
                <animate attributeName="width" values="0;20;20;20;0" begin="200ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="height" values="0;20;20;20;0" begin="200ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="x" values="35;25;25;25;35" begin="200ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="y" values="10;0;0;0;10" begin="200ms" dur="1000ms" repeatCount="indefinite"/>
            </rect>
            <rect width="20" height="20" x="50" y="0" rx="3" ry="3">
                <animate attributeName="width" values="0;20;20;20;0" begin="400ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="height" values="0;20;20;20;0" begin="400ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="x" values="60;50;50;50;60" begin="400ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="y" values="10;0;0;0;10" begin="400ms" dur="1000ms" repeatCount="indefinite"/>
            </rect>
            <rect width="20" height="20" x="75" y="0" rx="3" ry="3">
                <animate attributeName="width" values="0;20;20;20;0" begin="800ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="height" values="0;20;20;20;0" begin="800ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="x" values="85;75;75;75;85" begin="800ms" dur="1000ms" repeatCount="indefinite"/>
                <animate attributeName="y" values="10;0;0;0;10" begin="800ms" dur="1000ms" repeatCount="indefinite"/>
            </rect>
        </svg>
    </div>
    <div class="top">
        <p>
            <a href="/base/restaurant/index/res_id/{BEESCRM:$res_id}" class="iconfont icon-zuo pull-left"></a>
            <a href="/base/restaurant/restaurant/id/{BEESCRM:$restaurantId}/res_id/{BEESCRM:$res_id}"
               class="store-name pull-left">{BEESCRM:$info['restaurant_name']}<span
                    class="iconfont icon-you"></span></a>
            <a href="/base/restaurant/index/res_id/{BEESCRM:$res_id}" class="iconfont icon-shouye pull-right"></a>
        </p>
    </div>
    <div class="tb-mode menu">
        <div class="tb-cell classify"><span class="iconfont icon-fenlei"></span>分类</div>
        <!--<div class="tb-cell theme nav-title">特色菜</div>-->
    </div>
    <div class="menu-lists">
        <p class="close">关闭 <span class="iconfont icon-guanbi"></span></p>
        <volist name="data" id="vo">
            <a href="#" data-categoryid="{BEESCRM:$vo.category_id}">{BEESCRM:$vo.category_name}</a>
        </volist>
    </div>
    <div class="product-lists"></div>
    <div class="total-info"></div>
</div>
<div class="pop-box pop1"></div>
<div class="cart-box">

</div>
<!--模态窗-->
<div class="md-modal md-effect-1" id="modal-1">
    <div class="md-content">
        <div class="get-modal-content">
            <div class="inner-content"></div>
            <button class="md-close" data-modal="modal-1"><span class="iconfont icon-close"></span></button>
        </div>
    </div>
</div>
<!--菜品大图弹窗后的黑色背景-->
<div class="md-overlay" data-modal="modal-1"></div>

<input type="hidden" value="{BEESCRM:$restaurantId}" id="restaurantIdInput">
<input type="hidden" value="{BEESCRM:$categoryId}" id="categoryIdInput">

<script type="text/x-handlebars-template" id="product-tpl">
    {{#each product.goods_list}}
    <div class="lists tb-mode foods-menu">
        <a href="#" class="tb-cell list-left show-box" data-idx="{{@index}}" data-modal="modal-1">
            <div class="img-box"><img src="{{goods_logo}}"></div>
        </a>

        <div class="tb-cell list-center">
            <p>{{goods_name}}</p>
            <div class="tb-mode">
                <div class="tb-cell">
                    <p class="count"><span class="iconfont icon-huo"></span> {{goods_sum}} 份</p>
                    {{#if discount}}
                        <p class="prize">￥{{discount}}元</p>
                        <span class="old-prize" style="text-decoration:line-through;">￥{{price}}元</span>
                    {{else}}
                        <span class="prize">￥{{price}}元</span>
                    {{/if}}
                </div>
                <div class="tb-cell list-right">
                    <div class="tb-mode amount">
                        <a href="#" class="tb-cell change-num-btn" data-goodsid="{{goods_id}}" data-status="sub">-</a>
                        <input type="text" class="tb-cell buy-count buy-count-{{goods_id}}" value="{{sale_num}}"
                               data-goodsid="{{goods_id}}" data-status="input"/>
                        <a href="#" class="tb-cell change-num-btn" data-goodsid="{{goods_id}}" data-status="plus">+</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {{/each}}
</script>
<script type="text/x-handlebars-template" id="cart-tpl">
    <div class="lists tb-mode fixed-amount">
        <div class="tb-cell list-left" id="cart">
            <p><span class="iconfont icon-weiwaimai"></span><span
                    class="lot cart-num">{{product.cart_sum}}</span></p>
        </div>
        <div class="tb-cell list-center">
            <p class="count">{{product.min_price}}元起送</p>
            <p><span id="total-cost">{{product.cart_cost}}</span>元</p>
        </div>
        <div class="tb-cell list-right go-to-pay">
            <a href="javascript:;" class="pay">去结算</a>
        </div>
    </div>
</script>

<include file="commonJS"/>

<script>
    $(window).load(function(){
        //窗口加载完成显示左侧分类
        $('.menu-lists').addClass('show-menu');
    });
    $('.classify').click(function (e) {
        //放置点击事件向父元素传播
        e.stopPropagation();
        //点击“分类”显示左侧分类
        $('.menu-lists').addClass('show-menu');
    });
    $('.close').click(function (e) {
        //同上
        e.stopPropagation();
        //点击“关闭”取消左侧分类
        $('.menu-lists').removeClass('show-menu');
    });
    $(document).on('click', function () {
        //点击空白处取消左侧分类
        $('.menu-lists').removeClass('show-menu');
    });

    //pop-box是购物车弹出时的黑色背景
    $('.pop-box').click(function () {
        //点击黑色背景后背景消失
        $('.pop-box').fadeOut(300);
        //购物车回到底部
        $('.cart-box').removeClass('up');
    });

    //设置左侧分类弹窗高度
    var height = $(window).height();
    $('.menu-lists').css("height",height-89);

    //handlebar渲染页面
    $(function () {
        //初始化要渲染的部分
        var productSource = $("#product-tpl").html();
        var productTpl = Handlebars.compile(productSource);
        var elem = $('.product-lists');
        var cartSource = $("#cart-tpl").html();
        var cartTpl = Handlebars.compile(cartSource);
        //
        var totalContainer = $('.total-info');
        var restaurantId = $('#restaurantIdInput').val();
        var categoryId = $('#categoryIdInput').val();

        var cartList = {}, goods;

        //金额四舍五入 把模板里的cost进行下面的处理
        Handlebars.registerHelper('cost',function(option){
            //四舍五入
            return Number(option).toFixed(2);
        });

        //点击左侧分类弹窗的a标签时
        $('.menu-lists').on('click', 'a', function (e) {
            //取消元素的所有默认事件
            e.preventDefault();
            categoryId = $(this).data('categoryid');
            //替换标题
            $('.nav-title').text($(this).text());
            //渲染菜单函数
            renderGoodsList(restaurantId, categoryId);
        });

        //渲染购买数量
        //id：商品id status：加或减
        function renderNumVal(data, id, status, callback) {
            var initNum,
                    regNum = /^\+?(0|[1-9]\d*)$/;

            var numData = data.filter(function (v, i) {
                //过滤元素，留下符合条件的(应该是只有一个)
                return v.goods_id == id;
            });

            //？
            initNum = parseInt(numData[0].sale_num);
            //获取现在点了几份
            initNum = $('.buy-count-' + id + '').val();

            //根据加或减改变值
            if (status == 'plus') {
                initNum++;
            } else if (status == 'sub') {
                //？
                if (initNum < 1) {
                    delete cartList[id];
                    initNum = 0;
                    return false;
                }
                initNum--;
                if (initNum < 1) {
                    delete cartList[id];
                }
            } else if (status == 'input') {
                initNum = $('.buy-count-' + id + '').val();

                if (initNum < 1 || !regNum.test(initNum)) {
                    initNum = 0;
                    delete cartList[id];
                    $('.buy-count-' + id + '').val(initNum);
                }
            }

            //?
            data.map(function (v, i) {
                if (v.goods_id == id) {
                    return v.sale_num = initNum;
                }
            });

            //改变页面份数值
            $('.buy-count-' + id + '').val(initNum);

            //改变数据库物品数量
            $.get('/base/restaurant/updateCartNum/res_id/{BEESCRM:$res_id}', {
                goods_id: id,
                sale_num: initNum,
                restaurant_id: restaurantId
            }, function (res) {
                var result = $.parseJSON(res);
                if (result.status === 'S') {
                    //重新渲染页面并判断是否可以付款
                    totalContainer.html(cartTpl({product: result.data}));
                    isToPay();

                    if(callback && typeof callback == 'function') {
                        callback(initNum,result.data.goods_price);
                    }
                } else {
                    alert(result.message);
                }
            });
        }

        //数量增减
        elem.on('click', '.change-num-btn', function () {
            var id = $(this).data('goodsid'),
                    status = $(this).data('status');
            renderNumVal(goods.data.goods_list, id, status);
        });

        //输入数量
        elem.on('change', '.buy-count', function () {
            var id = $(this).data('goodsid'),
                    status = $(this).data('status');
            renderNumVal(goods.data.goods_list, id, status);
        });

        //结算
        totalContainer.on('click', '.go-to-pay', function (e) {
            e.preventDefault();
            isToPay();
            $.get('/base/restaurant/getOrderUrl/res_id/{BEESCRM:$res_id}', {restaurant_id:restaurantId}, function (res) {
                var result = $.parseJSON(res);
                if (result.status == 'S') {
                    location.href = result.url;
                } else {
                    $.alert('error',result.message);
                }
            });
        });
        //判断是否可以结算
        function isToPay() {
            //+ ?
            if(+goods.data.min_price > +$('#total-cost').text()) {
                $('.go-to-pay').addClass('disabled-pay');
                return false;
            } else {
                $('.go-to-pay').removeClass('disabled-pay');
            }
        }

        //载入数据（第一次进入没有点击左侧分类时显示默认的）
        renderGoodsList(restaurantId, categoryId);

        function renderGoodsList(restaurant, categoryId){
            $.getAjax({
                url: '/base/restaurant/getGoodsInfo/res_id/{BEESCRM:$res_id}',
                method: 'GET',
                data: {
                    restaurant_id: restaurant,
                    category_id: categoryId
                }
            }, false, function (res) {
                goods = res || {};
                if (res.status == 'S') {
                    restaurantId = res.data.restaurant_id;
                    //把这个分类下的菜品数据渲染页面

                    if(!res.data.discount){
                    }else{
                        delete json["discount"];
                    }
                    elem.html(productTpl({product: res.data}));
                    totalContainer.html(cartTpl({product: res.data}));
                    isToPay();
                }
            });
        }

        //菜品大图弹窗
        elem.off('click', '.show-box').on('click', '.show-box', function () {
            var idx = $(this).data('idx');
            var modal = $(this).data('modal');
            $('#' + modal).addClass('md-show');
            $('.inner-content').html('<img src="' + goods.data.goods_list[idx].goods_logo + '"><p>' + goods.data.goods_list[idx].goods_desc + '</p>');
        });

        //点击左上角关闭按钮或黑色背景取消弹窗
        $(document).on('click', '.md-close, .md-overlay', function (e) {
            var modal = $(this).data('modal');
            $('#' + modal).removeClass('md-show');
        });

        //弹出购买清单
        $(document).on('click', '#cart', function () {
            $.getAjax({
                url:'/base/restaurant/getCartInfo/res_id/{BEESCRM:$res_id}',
                method:'GET',
                data:{restaurant_id: restaurantId}
            }, false, function (res) {
                popGoodList = res.data;
                renderPopCart(res.data);
                $('.cart-box').toggleClass('up');
                $('.pop-box').toggle();

            });
        });

        //点击弹出购物车之后的黑色背景 渲染菜单列表
        $(document).on('click', '.pop1', function () {
            renderGoodsList(restaurantId, categoryId);
        });

        //数量增减
        $('.cart-box').on('click', '.change-num-btn', function () {
            var id = $(this).data('goodsid'),
                    status = $(this).data('status'),
                    that = $(this);
            renderNumVal(popGoodList, id, status, function (num,price) {
                //回调函数：离.change-cart-num按钮最近的祖先元素的所有含有.foods-num的同胞元素
                that.closest('.change-cart-num').siblings('.foods-num').text(num + '份');
                that.closest('.change-cart-num').siblings('.foods-prize').text(price + '元');
            });
        });
        //输入数量
        $('.cart-box').on('change', '.buy-count', function () {
            var id = $(this).data('goodsid'),
                    status = $(this).data('status'),
                    that = $(this);
            $('.buy-count-' + id).val(that.val());
            renderNumVal(popGoodList, id, status, function (num,price) {
                that.closest('.change-cart-num').siblings('.foods-num').text(num + '份');
                that.closest('.change-cart-num').siblings('.foods-prize').text(price + '元');
            });
        });

        function renderPopCart(data) {
            var tpl = '';
            $.each(data, function (i,v) {
                tpl += '<div class="foods-list clearfix"><span class="foods-name">'+ v.goods_name +'</span><span class="foods-num">'+ v.sale_num +'份</span>' +
                        '<span class="foods-prize">'+ Number(v.price).toFixed(2) +'元</span>'
                + '<div class="clearfix change-cart-num"><span class="iconfont icon-shanchu delete-goods" data-idx="'+ i +'" data-goodsid="'+ v.goods_id +'"></span><div class="tb-mode amount">'
                +'<a href="#" class="tb-cell change-num-btn" data-goodsid="'+ v.goods_id +'" data-status="sub">-</a>'
                +'<input type="text" class="tb-cell buy-count buy-count-'+ v.goods_id +'" value="'+ v.sale_num +'"'
                +'data-goodsid="'+ v.goods_id +'" data-status="input"/>'
                +'<a href="#" class="tb-cell change-num-btn" data-goodsid="'+ v.goods_id +'" data-status="plus">+</a>'
                +'</div></div>'
                +'</div>';
            });
            $('.cart-box').html(tpl);
        }

        $('.cart-box').on('click', '.foods-list', function () {
            $(this).find('.change-cart-num').show();
            $(this).siblings('.foods-list').find('.change-cart-num').hide();
        });
        $('.cart-box').on('click', '.delete-goods', function () {
            var id = $(this).data('goodsid'),
                    idx = $(this).data('idx');

            $.get('/base/restaurant/updateCartNum/res_id/{BEESCRM:$res_id}', {
                goods_id: id,
                sale_num: 0,
                restaurant_id: restaurantId
            }, function (res) {
                var result = $.parseJSON(res);
                if (result.status === 'S') {
                    popGoodList.splice(idx, 1);
                    goods.data.goods_list.map(function (v, i) {
                        if (v.goods_id == id) {
                            return v.sale_num = 0;
                        }
                    });

                    $('.buy-count-' + id + '').val(0);
                    renderPopCart(popGoodList);
                    totalContainer.html(cartTpl({product: $.parseJSON(res).data}));
                } else {
                    alert(result.message);
                }
            });
        });
    });
</script>
<script src="/assets/base/restaurant/js/classie.js"></script>
</body>
</html>
